<?php

namespace App\Http\Controllers\Teacher;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\Roles;
use App\Model\Permission;
use App\Tools\HgTool;
use Auth,Session;

class CommonController extends Controller
{
	//验证用户是否登录并且获取当前用户的信息
    public function __construct(){

    	$this->middleware(function($request, $next) {
            //判断是否登录
	    	if (Auth::check()){
	    		$user_info = Auth::user();	// 将信息取得
                Session::put('user_info', $user_info);  // 存入seesion
                
	    	}else{
	    		return redirect()->route('login');	// 如果没有登录就返回登录页面
	    	}

            //判断是否是管理员
            if(empty($user_info->is_teacher)){
                return redirect()->route('logout');  // 如果没有登录就返回登录页面
            }

            //判断是否有权限访问rbac
            $tool = new HgTool;
            $controller = $tool->getMethod()[0];
            $roles = new Roles;
            $permission = new Permission;
            $permissionId = $roles->find($user_info->roles)['pid'];

            if($permissionId != 0 && $controller != 'Index'){
                $permissionArr = $tool->arrToArr($permission->whereIn('id',explode(',',$permissionId))->get(),'permission');
                // $user_info['controller'] = $controller; //当前控制器也存入
                Session::put('permission',$permissionArr); //权限信息也存入

                if( !in_array($controller,$permissionArr)){
                    return redirect('/Teacher/index');
                }
            }
           
            //view()->share('loginUser', $this->loginUser);
            return $next($request);
        });
    	

    }
}
